#include "linked_list.h"
#include "thread_pool.h"
#include "user.h"


extern ListNode* userList;

//主线程调用：处理客户端法国来的消息
//接收客户端消息、封装任务并提交到线程池
void handleMessage(int sockfd,int epfd,task_queue_t* que){
    //消息格式：cmd content
    //1.1 获取消息长度
    int length=-1;
    int ret = recvn(sockfd,&length,sizeof(length));
    int cmdType=-1;
    task_t* ptask;
    if(ret==0){
        goto end;
    }
    printf("\n\nrev length:%d\n",length);

    //1.2获取消息类型
    
    ret =recvn(sockfd,&cmdType,sizeof(cmdType));
    if(ret==0){
        goto end;
    }
    printf("recv cmd type:%d\n",cmdType);

    ptask = (task_t*)calloc(1,sizeof(task_t));

    ptask->peerfd = sockfd;
    ptask->epfd=epfd;
    ptask->type =(CmdType)cmdType;
    if(length>0){
        //1.3 获取消息内容
        ret = recvn(sockfd,&ptask->data,length);
        if(ret>0){
            //往线程池中添加任务
            if(ptask->type==CMD_TYPE_PUTS){
                //上传文件任务，删除epoll的监听
                delEpollReadfd(epfd,sockfd);
            }
            taskEnque(que,ptask);
        }
    }else if(length==0){
        taskEnque(que,ptask);
    }
end:
    if(ret==0){
        printf("\n conn %d is closed.\n",sockfd);
        delEpollReadfd(epfd,sockfd);
        close(sockfd);
        deleteNode2(&userList,sockfd);
    }
}
